<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>WebRTC 调试页面</title>
    <style>
        body { font-family: Arial; padding: 20px; }
        label, input, textarea, button { display: block; width: 100%; margin-top: 10px; }
        video {
            width: 100%;
            max-width: 800px;
            margin-top: 20px;
            background-color: black;
        }
    </style>
</head>
<body>

<h2>WebRTC 拉流测试</h2>

<div>
    <label for="app">应用名称 (app)</label>
    <input type="text" id="app" value="live">
</div>

<div>
    <label for="stream">流标识 (stream)</label>
    <input type="text" id="stream" value="camera_001">
</div>

<div>
    <label for="type">SDP 类型 (type): play / push / echo</label>
    <input type="text" id="type" value="play">
</div>

<div>
    <label for="pcSdp">PC SDP 内容 (pcSdp)</label>
    <textarea id="pcSdp"></textarea>
</div>

<button onclick="generateOffer()">生成 Offer 并播放</button>
<button onclick="stopPlayback()">关闭播放</button>  <!-- 新增按钮 -->
<button onclick="testBackend()">测试后端接口</button>

<video id="videoElement" autoplay playsinline controls></video>
<!--<video controls autoplay>-->
<!--    <source src="flv://192.168.0.198:8180/live/camera_001.live.flv" type="video/x-flv">-->
<!--    您的浏览器不支持 video 标签。-->
<!--</video>-->

<script>
    // const serverUrl = "http://192.168.0.239:8180"; // 替换为你的本地服务地址
    // const serverUrl = "http://192.168.0.198:8899"; // 替换为你的本地服务地址
    // const serverUrl = "http://192.168.0.239:8899"; // 替换为你的本地服务地址
    const serverUrl = "https://media.shenglong.com"; // 替换为你的本地服务地址
    let pc = null;

    var myHeaders = new Headers();
    myHeaders.append("secret", "035c73f7-bb6b-4889-a715-d9eb2d1925cc");
    myHeaders.append("User-Agent", "Apifox/1.0.0 (https://apifox.com)");
    myHeaders.append("Accept", "*/*");
    myHeaders.append("Host", serverUrl);
    myHeaders.append("Connection", "keep-alive");
    myHeaders.append("Origin", serverUrl); // 添加 origin
    myHeaders.append("Referer", serverUrl); // 添加 referer


    var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        mode: 'cors', // 显式声明使用 CORS
        credentials: 'same-origin', // 如果需要携带 Cookie 可以设为 include
        redirect: 'follow'
    };
    async function generateOffer() {
        console.log("【DEBUG】generateOffer 开始");

        const app = document.getElementById('app').value.trim();
        const stream = document.getElementById('stream').value.trim();
        const type = document.getElementById('type').value.trim();
        const pcSdpInput = document.getElementById('pcSdp');
        const videoElement = document.getElementById('videoElement');

        pc = new RTCPeerConnection();

        // 添加调试日志
        pc.onicecandidate = async (event) => {
            console.log("【ICE Candidate】新候选地址:", event.candidate);
            if (event.candidate) {
                // 构造请求头，避免使用多个 Content-Type
                const headers = new Headers();
                headers.append("secret", "035c73f7-bb6b-4889-a715-d9eb2d1925cc");
                headers.append("Origin", serverUrl);
                headers.append("Referer", serverUrl);
                headers.append("Content-Type", "application/json");  // 使用 text/plain 避免 MIME 错误

                // 将 candidate 发送到信令服务器
                fetch(`${serverUrl}/index/api/webrtc_ice`, {
                    method: 'POST',
                    headers: headers,
                    body: JSON.stringify(event.candidate)
                });
            }
        };

        pc.ontrack = (event) => {
            console.log("【Track】收到远程流");
            if (!videoElement.srcObject) {
                videoElement.srcObject = event.streams[0];
            }
        };

        pc.onconnectionstatechange = () => {
            console.log("【连接状态变化】", pc.connectionState);
        };

        // 添加音视频收发器
        pc.addTransceiver("video", {direction: 'recvonly'});
        pc.addTransceiver("audio", {direction: 'recvonly'});

        try {
            // 创建 Offer
            const offer = await pc.createOffer();
            console.log("✅ 成功创建 Offer SDP");

            // 设置本地描述
            await pc.setLocalDescription(offer);
            console.log("📌 已设置 localDescription");

            const response = await fetch(`${serverUrl}/index/api/webrtc?app=${encodeURIComponent(app)}&stream=${encodeURIComponent(stream)}&type=play`, {
                method: 'POST',
                headers: {

                    'Content-Type': 'text/plain;charset=UTF-8',
                    'secret': '035c73f7-bb6b-4889-a715-d9eb2d1925cc',
                    'Origin': serverUrl,
                    'Referer': serverUrl
                },
                body: pc.localDescription.sdp
            });

            const data = await response.json();  // 解析为 JSON
            console.log("📨 接口响应数据:", data);

            if (data.code === 0 && data.sdp) {
                const answerDesc = new RTCSessionDescription({
                    type: 'answer',
                    sdp: data.sdp  // 使用返回的 SDP 构造 Answer
                });

                await pc.setRemoteDescription(answerDesc);
                console.log("✅ 成功设置 remoteDescription");
            } else {
                alert("❌ 获取 Answer SDP 失败：" + (data.message || data.data));
            }
        } catch (error) {
            console.error("⚠️ 发生错误:", error);
            alert("发生错误：" + error.message);
        }
    }



    // 新增函数：关闭播放
    function stopPlayback() {
        console.log("【关闭播放】开始");

        if (pc) {
            pc.close();
            pc = null;
        }

        const videoElement = document.getElementById('videoElement');
        if (videoElement.srcObject) {
            videoElement.srcObject = null;
        }

        alert("✅ 播放已关闭");
    }
    async function testBackend() {

        myHeaders.append("Content-Type", "application/json");
        const url = `${serverUrl}/index/api/getMediaList?app=live&schema=rtsp&stream=camera_001&secret=035c73f7-bb6b-4889-a715-d9eb2d1925cc`;
        try {
            const res = await fetch(url, requestOptions);
            const data = await res.json();
            console.log("🔗 后端接口返回:", data);
            alert("✅ 后端接口可访问");
        } catch (e) {
            console.error("❌ 连接失败:", e);
            alert("❌ 后端接口不可访问，请检查服务是否运行");
        }
    }
</script>

</body>
</html>